import { Meteor } from "meteor/meteor";
import { check } from "meteor/check";
import { db } from "../../../config/db/connectiondb.ts";
import AdminUsers from "../models/AdminUsers.ts";
import bcrypt from "bcrypt";
import jwt from "jsonwebtoken";
import AdminMenus from "../models/AdminMenus.ts";

//生成token
export function generateToken(payload) {
  const secretKey = Meteor.settings?.private?.jwtSecret;
  if (!secretKey) {
    return false
  }
  return jwt.sign(payload, secretKey, { expiresIn: "2h" });
}


Meteor.methods({
  async userLogin({ username, password, captcha }) {
    // 参数类型校验，避免注入
    check(username, String);
    check(password, String);
    check(captcha, String);

    // 验证码校验
    if (!captcha || captcha.toLowerCase() !== global.currentCaptcha) {
      return new Meteor.Error(400, '验证码错误!');
    }

    // 查找用户
    const user = await AdminUsers.query().where("username", username).first();
    if (!user) {
      return new Meteor.Error(400, '用户不存在!');
    }

    // 密码比对（不要再hash一次，直接比对）
    const isMatch = await bcrypt.compare(password, user.toData().password);
    if (!isMatch) {
      return new Meteor.Error(400, '密码错误!');
    }

    // 生成 token
    const token = generateToken({
      userId: user.toData().id,
      username: user.toData().username,
      name: user.toData().name,
    });
    if (!token) {
      return new Meteor.Error(400, "生成token失败,请检查配置,启动方式【meteor --settings settings.json】");
    }
    // 成功返回
    return {
      status: 0,           // 0 表示成功
      message: '登录成功!',
      data: {
        token,
        user: {
          id: user.toData().id,
          username: user.toData().username,
          nickname: user.toData().nickname,
        },
      },
    };
  },
  //获取系统菜单列表
  async getMenusList(token) {
    const secretKey = Meteor.settings?.private?.jwtSecret || "defaultSecret";
    let userInfo;
    try {
      // 验证 token，有效期 & 签名
      userInfo = jwt.verify(token, secretKey);
    } catch (err) {
      if (err.name === 'TokenExpiredError') {
        throw new Meteor.Error(401, 'Token 已过期，请重新登录');
      } else {
        throw new Meteor.Error(403, '无效的 Token');
      }
    }
    //console.log("userInfo", userInfo);
    const menus = await getUserPermission(userInfo.userId);
    const menuMap = {};
    menus.forEach((menu) => {
      menuMap[menu.id] = {
        id: menu.id,
        parent_id: menu.parent_id,
        url_type: menu.url_type,
        label: menu.title,
        url: menu.url,
        component: menu.component,
        icon: menu.icon,
        schemaApi: menu.url,
        children: [],
      };
    });

    // 构建树形结构
    const tree = [];
    menus.forEach((menu) => {
      const node = menuMap[menu.id];
      if (menu.parent_id === 0) {
        tree.push(node);
      } else if (menuMap[menu.parent_id]) {
        menuMap[menu.parent_id].children.push(node);
      }
    });
    // 处理：如果有 children，则只保留 label 和 icon
    const simplifyNode = (node) => {
      //console.log("node", node);
      if (node.children && node.children.length > 0) {
        return {
          label: node.label,
          icon: node.icon,
          children: node.children.map(simplifyNode),
        };
      } else {
        const result = {
          label: node.label,
          icon: node.icon,
        };

        switch (node.url_type) {
          case 1: // 路由页面
            result.url = node.url;
            result.schemaApi = "/admin-api" + node.schemaApi;
            break;

          case 2: // 外链
            result.link = node.url;
            result.blank = true;
            break;

          case 3: // iframe 内嵌页面
            result.url = node.url;
            result.schema = {
              type: "page",
              body: [
                {
                  type: "iframe",
                  src: node.url,
                  height: 600,
                  style: {
                    border: "none"
                  }
                }
              ]
            };
            break;

          case 4: // 自定义页面
            result.url = node.url;
            result.schema = {
              type: "page",
              body: [
                {
                  type: "html",
                  html: node.component || "<div>暂无内容</div>"
                }
              ]
            };
            break;

          default:
            // 未知类型，默认当作路由
            result.url = node.url;
            result.schemaApi = "/admin-api" + (node.schemaApi || "");
            break;
        }

        return result;
      }
    };


    const simplifiedTree = tree.map(simplifyNode);
    //console.log("simplifiedTree", JSON.stringify(simplifiedTree));
    // 构造 app 对象
    const app = {
      type: "app",
      brandName: "Admin",
      logo: "https://doc.owladmin.com/logo.png",
      header: {
        type: "flex",
        justify: "between",
        className: "w-full p-2",
        items: [
          {
            type: "tpl",
            tpl: "顶部区域左侧",
            className: "text-lg font-bold",
          },
          {
            type: "dropdown-button",
            label: `${userInfo.name}`,
            level: "link",
            trigger: "hover",
            className: "ml-auto",
            buttons: [
              {
                label: "主题设置",
                actionType: "dialog",
                dialog: {
                  title: "主题设置",
                  body: "这里是主题设置内容",
                },
              },
              {
                label: "个人设置",
                actionType: "dialog",
                dialog: {
                  title: "个人设置",
                  body: "这里是个人设置内容",
                },
              },
              {
                label: "退出登录",
                actionType: "url",
                url: "/admin?logout=true",
              },
            ],
          },
        ],
      },
      pages: [
        {
          children: simplifiedTree,
        },
      ],
    };

    return app;
  },
});

//用户脚色权限查找
async function getUserPermission(userId) {
  if (userId === 1) {
    const menus = await AdminMenus.query().get();
    return menus.toArray();
  }
  try {
    // 获取用户角色及其权限
    const roles = await db
      .table("admin_roles")
      .join("admin_role_users", "admin_role_users.role_id", "admin_roles.id")
      .where("admin_role_users.user_id", userId)
      .select("admin_roles.id", "admin_roles.name")
      .then((result) => result || []);
    //console.log("roles", roles);
    if (!roles.length) {
      return errorResponse({ msg: "没有分配角色!" });
    }
    // 获取角色对应的权限和菜单数据
    const menus = await db
      .table("admin_menus")
      .join(
        "admin_permission_menu",
        "admin_permission_menu.menu_id",
        "admin_menus.id"
      )
      .join(
        "admin_role_permissions",
        "admin_role_permissions.permission_id",
        "admin_permission_menu.permission_id"
      )
      .whereIn(
        "admin_role_permissions.role_id",
        roles.map((role) => role.id)
      )
      .where("admin_menus.visible", 1)
      .orderBy("admin_menus.custom_order", "asc")
      .select("admin_menus.*")
      .distinct()
      .then((result) => result || []);
    if (!menus.length) {
      return errorResponse({ msg: "没有可访问的菜单!" });
    }

    return menus;
  } catch (error) {
    console.error("获取用户权限异常:", error);
    return errorResponse({ msg: "系统错误，请稍后重试" });
  }
}